#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
using namespace std;
#include "Mutex.hpp"

int ticket = 10000;

// 全局锁
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *getTicket(void *args)
{
    const char *thread_name = static_cast<const char *>(args);
    while (true)
    {
        // 加锁
        // pthread_mutex_lock(&lock);
        {
            LockGuard lockguard(&lock);
            if (ticket > 0)
            {
                usleep(1000);
                cout << thread_name << " 正在抢票 " << ticket << endl;
                ticket--;
                // pthread_mutex_unlock(&lock);
            }
            else
            {
                // pthread_mutex_unlock(&lock);
                break;
            }
        }
        // 抢完票之后，会做一个汇总
        usleep(1000);
    }

    return nullptr;
}

int main()
{
    pthread_t tid1, tid2, tid3, tid4;
    // 创建多个线程，进行抢票
    pthread_create(&tid1, nullptr, getTicket, (void *)"thread 1");
    pthread_create(&tid2, nullptr, getTicket, (void *)"thread 2");
    pthread_create(&tid3, nullptr, getTicket, (void *)"thread 3");
    pthread_create(&tid4, nullptr, getTicket, (void *)"thread 4");

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);
    pthread_join(tid4, nullptr);
    return 0;
}
